using UnityEngine;

public class PlayerController : PlayerInput
{
    Rigidbody _rb;

    [Header("移动")]
    Vector3 _playerMoveInput;// 玩家移动向量
    [SerializeField] float _speed = 1000f;// 移动的速度

    [Header("相机视角控制")]
    public Transform CameraFollow;// 用于跟随摄像机的 Transforms
    private Vector3 _playerLookInput;// 玩家视角输入
    private float _playerRotation;// 角色旋转角度
    private float _cameraPitch;// 摄像机俯仰角度
    [SerializeField] float _rotationSpeed = 180.0f;// 角色旋转速度
    [SerializeField] float _pitchSpeed = 180.0f;// 摄像机俯仰速度
    
    private Camera mainCamera; // 主相机

    private void Awake()
    {
        _rb = GetComponent<Rigidbody>();
        mainCamera = Camera.main; // 获取主相机
    }

    private void Update()
    {
        _playerLookInput = new Vector3(LookInput.x, -LookInput.y, 0f) * Time.deltaTime;// 获取视角输入
        PlayerLook(); // 更新角色的旋转
        PitchCamera(); // 更新摄像机的俯仰角度
    }

    private void FixedUpdate()
    {
        PlayerMove();
    }

    // 计算并应用玩家的移动
    private void PlayerMove()
    {
        // 根据输入和速度计算移动向量
        _playerMoveInput = new Vector3(MoveInput.x, 0, MoveInput.y).normalized * _speed;
        // 将相对力应用到刚体上
        _rb.AddRelativeForce(_playerMoveInput, ForceMode.Force);
    }

    // 更新角色的旋转
    private void PlayerLook()
    {
        _playerRotation += _playerLookInput.x * _rotationSpeed;
        _rb.rotation = Quaternion.Euler(0f, _playerRotation, 0f);
    }

    // 更新摄像机的俯仰角度
    private void PitchCamera()
    {
        Vector3 rotationValues = CameraFollow.rotation.eulerAngles;
        _cameraPitch += _playerLookInput.y * _pitchSpeed;
        _cameraPitch = Mathf.Clamp(_cameraPitch, -89.9f, 89.9f);//限制俯仰视角角度
        CameraFollow.rotation = Quaternion.Euler(_cameraPitch, rotationValues.y, rotationValues.z);
    }
}
